<script>
import {getSy, saveTicket, updataTicket} from "@/api/api";
import EventBus from "@/utils/eventBus";

export default {
    name: "newTicketModel",
    data() {
        return {
            localnewTicketModel: false,
            ticketId: undefined,
            isMinimized: false,
            dialogStyle: { top: "50%", left: "50%", transform: "translate(-50%, -50%)",cursor:'pointer' },
            isDragging: false,
            startX: 0,
            startY: 0,
            offsetX: 0,
            offsetY: 0,
            direction:'',
            currentIndex:-1,
            history:[],
            createType:undefined,
            tableData:[
            ],
            ticketName:'',
            shuyuData:[],
            currentData:{
                index:undefined,
                recordDesc:'',
                operatePointName:'',
                operateState:undefined,
            },
            selectedRowIndex: null, // 当前选中的行索引
            selectedSyRowIndex:null,
            syCurrentData:{
            },
            ws:null
        };
    },
    methods: {
        saveTicketId(val){
          this.ticketId=val
        },
        close() {
            if (this.$store.state.setTicketType==='图形开票'){
                this.ws.send(JSON.stringify({"cmd":"kpczState","state":"0"}))
                return
            }
            this.$emit("ticketClose");
            this.clear();
            this.dialogStyle = { top: "50%", left: "50%", transform: "translate(-50%, -50%)" ,cursor:'pointer'};
        },
        minimize() {
            this.isMinimized = true;
            this.dialogStyle = {
                top: "auto",
                left: "16rem",
                bottom: "0",
                width: "200px",
                height: ".9rem",
                transform: "none",
                border: "1px solid #fff",
                fontSize: "12px",
                cursor:'pointer',
                zIndex: 2000,
            };
            this.removeDragListeners();
        },
        restore() {
            this.isMinimized = false;
            this.dialogStyle = { top: "50%", left: "50%", transform: "translate(-50%, -50%)",cursor:'pointer'};
            this.addDragListeners();
        },
        onMouseDown(event) {
            if (this.isMinimized) return;
            this.isDragging = true;
            this.startX = event.clientX;
            this.startY = event.clientY;
            this.offsetX = this.$refs.dialog.offsetLeft;
            this.offsetY = this.$refs.dialog.offsetTop;
            document.body.style.userSelect = "none";
            document.addEventListener("mousemove", this.onMouseMove);
            document.addEventListener("mouseup", this.onMouseUp);
        },
        onMouseMove(event) {
            if (!this.isDragging) return;
            const dx = event.clientX - this.startX;
            const dy = event.clientY - this.startY;
            this.dialogStyle = {
                ...this.dialogStyle,
                left: `${this.offsetX + dx}px`,
                top: `${this.offsetY + dy}px`,
            };
        },
        onMouseUp() {
            this.isDragging = false;
            document.removeEventListener("mousemove", this.onMouseMove);
            document.removeEventListener("mouseup", this.onMouseUp);
            document.body.style.userSelect = "";
        },
        addDragListeners() {
            const dragHandle = this.$refs.dragHandle;
            if (dragHandle) {
                dragHandle.addEventListener("mousedown", this.onMouseDown);
            }
        },
        removeDragListeners() {
            const dragHandle = this.$refs.dragHandle;
            if (dragHandle) {
                dragHandle.removeEventListener("mousedown", this.onMouseDown);
            }
        },
        selectRow(index) {
                this.selectedRowIndex = index;
                this.tableData.forEach(item=>{
                    if (item.index===index){
                        this.currentData=item;
                    }
                })
        },
        selectSyRow(index){
            this.selectedSyRowIndex = index;
            this.shuyuData.forEach(item=>{
                if (item.index===index){
                    this.syCurrentData=item;
                }
            })
        },
        saveSnapshot(){
            console.log('开始加载')
            if (this.currentIndex < this.history.length - 1) {
                this.history = this.history.slice(0, this.currentIndex + 1);
            }
            this.history.push(JSON.parse(JSON.stringify(this.tableData)))
            this.currentIndex++;
        },
        undo() {
            if (this.currentIndex > 0) {
                this.currentIndex--;
                this.tableData = JSON.parse(JSON.stringify(this.history[this.currentIndex]));
            }else{
                this.$message.info('当前无操作可回退')
            }
            this.currentData={
                index:null,
                recordDesc:'',
                operatePointName:'',
                operateState:undefined
            }
        },
        addEvent(txt){
            this.selectedRowIndex=this.tableData.length+1;
            this.currentData={
                index:this.tableData.length+1,
                recordDesc:txt.recordDesc?txt.recordDesc:'',
                operateState:txt.operateState??undefined,
                operatePointName:txt.operatePointName?txt.operatePointName:'',
                operateType:txt.operateType?txt.operateType:"",
            }
            this.tableData.push(this.currentData);
            this.saveSnapshot();
        },
        removeEvent(){
            if (this.selectedRowIndex){
                this.tableData=this.tableData.filter(item=>item.index!==this.selectedRowIndex)
                this.selectedRowIndex=null;
                this.currentData={
                    index:null,
                    recordDesc:'',
                    operatePointName:'',
                    operateState:undefined
                }
                this.tableData.forEach((item,index)=>{
                    item.index=index+1;
                })
                this.saveSnapshot();

            }else{
                this.$message.info('请选择要删除的行')
            }
        },
        insertEvent(){
            if (this.tableData.length===0){
                this.syCurrentData={
                    index:this.selectedSyRowIndex,
                    recordDesc:this.syCurrentData.recordDesc,
                }
                this.tableData.push(JSON.parse(JSON.stringify(this.syCurrentData)))
                this.tableData.forEach((item,index)=>{
                    item.index=index+1;
                })
                this.saveSnapshot();
            }else if (this.selectedSyRowIndex&&this.direction&&this.selectedRowIndex){
                this.syCurrentData={
                    index:this.selectedSyRowIndex,
                    recordDesc:this.syCurrentData.recordDesc,
                }
                if (this.direction==='qian'){
                    this.tableData.splice(this.selectedRowIndex-1,0,this.syCurrentData);
                }else{
                    this.tableData.splice(this.selectedRowIndex,0,this.syCurrentData);

                }
                this.tableData.forEach((item,index)=>{
                    item.index=index+1;
                })
                this.saveSnapshot();
            }else{
                this.$message.info(`${this.selectedRowIndex===null?'请选择要插入的位置':this.selectedSyRowIndex===null?'请选择要插入的术语':'请选择要插入的方向'}`)
            }
        },
     async  submitTicket(){
            if (!this.ticketName){
                this.$message.error('请输入操作票名称')
            }else{
                const records = this.tableData.map(item =>
                    JSON.parse(JSON.stringify({
                        recordDesc: item.recordDesc,
                        operateState: item.operateState ?? '',
                        operatePointName: item.operatePointName?item.operatePointName:'',
                        operateType:item.operateType
                    }))
                );
                const submitData={
                    studentId:this.$store.state.user.id,
                    name:this.ticketName,
                    records:records,
                    createType:this.$store.state.setTicketType
                }
                const res= await saveTicket(submitData);
                if (res.data.code===200){
                    this.$message.success('保存为历史操作票成功')
                }else{
                    this.$message.error(res.data.msg)
                }
            }
        },
        async EditTicket(){
            if (!this.ticketName){
                this.$message.error('请输入操作票名称')
            }else{
                const records = this.tableData.map(item =>
                    JSON.parse(JSON.stringify({
                        recordDesc: item.recordDesc,
                        operateState: item.operateState ?? '',
                        operatePointName: item.operatePointName?item.operatePointName:'',
                    }))
                );
                const submitData={
                    id:this.ticketId,
                    name:this.ticketName,
                    studentId:this.$store.state.user.id,
                    records:records,
                    createType:this.createType
                }
                const res= await updataTicket(submitData);
                if (res.data.code===200){
                    this.$message.success('更新成功')
                }else{
                    this.$message.error(res.data.msg)
                }
            }
        },
        async initSy(){
            const res= await  getSy();
            if (res.data.code===200){
                this.shuyuData=res.data.data;
            }
            this.shuyuData.forEach((item,index)=>{
                item.index=index+1
            })
        },
        clear() {
            this.tableData=[]
            this.currentIndex=-1
            this.currentData={
                index:null,
                recordDesc:'',
                operatePointName:'',
                operateState:undefined
            }
            this.syCurrentData={
                index:null,
                recordDesc:'',
            }
            this.ticketName=''
        }
    },
    props: {
        newTicketModel: {
            type: Boolean,
            default: false,
        },
        currentEventObj:{
            type: Object,
            default: () => ({}),
        }
    },
    watch: {
        newTicketModel(newVal) {
            this.localnewTicketModel = newVal;
            if (newVal){
                this.initSy();
                if (!this.ws){
                    this.ws=this.$store.state.webSocket;
                    if (this.ws._listener) {
                        this.ws.removeEventListener('message', this.ws._listener); // 先移除旧的
                    }
                    this.ws._listener = (event) => { // 存储监听函数引用
                        let data = JSON.parse(event.data);
                        if (data.cmd === 'kpczState' && data.state !== '1') {
                            this.$emit("ticketClose");
                            this.clear();
                            this.dialogStyle = { top: "50%", left: "50%", transform: "translate(-50%, -50%)", cursor: 'pointer' };
                        }
                    };
                    this.ws.addEventListener('message', this.ws._listener);
                }
                if (this.currentEventObj){
                    if (this.currentEventObj.createType==='图形开票'){
                        this.$store.commit('setTicketType','图形开票')
                        this.ws.send(JSON.stringify({"cmd":"kpczState","state":"1"}))
                    }
                    this.tableData=this.currentEventObj?.records
                    this.ticketName=this.currentEventObj.name
                    this.ticketId=this.currentEventObj.id?this.currentEventObj.id:undefined
                    this.createType=this.currentEventObj?.createType
                }
                this.tableData.forEach((item,index)=>{
                    item.index=index+1;
                })
                this.saveSnapshot();
            }else{
                if (this.$store.state.setTicketType==='图形开票'){
                    this.$store.commit('setTicketType','')
                    this.ws.send(JSON.stringify({"cmd":"kpczState","state":"0"}))
                }
                this.currentEventObj=null;
            }
        },
        handleTicketContent(newVal) {
            if (newVal!==''){
                this.addEvent(newVal)
            }
        },
    },
    mounted() {
        this.$nextTick(() => {
            this.addDragListeners(); // 初始加载时绑定拖动事件
        });
        EventBus.on('saveTicketId',this.saveTicketId);

    },
    beforeDestroy() {
        this.removeDragListeners(); // 销毁前移除拖动事件
    },
    computed: {
        handleTicketContent() {
            console.log(123)
            return this.$store.state.ticketHandleContent;
        },
    },

};
</script>

<template>
    <div v-show="localnewTicketModel" class="custom-dialog-wrapper">
        <div
            class="custom-dialog"

            ref="dialog"
            :class="{ 'minimized': isMinimized }"
        :style="dialogStyle">
        <header class="custom-dialog-header" ref="dragHandle" v-if="!isMinimized" style="cursor: move">
            <span>查看操作票</span>
            <div class="header-buttons">
                <el-button  class="minimize-button" size="medium" @click="minimize" style="border: none;background-color: transparent;color: white" icon="el-icon-caret-bottom">
                </el-button>
                <button class="close-button" @click="close" >×</button>
            </div>
        </header>
            <header class="custom-dialog-header" ref="dragHandle" v-if="isMinimized" style="font-size: 14px">
                <span style="margin-top: -1rem">查看操作票</span>
                <div class="header-buttons">
                    <el-button  size="medium"  class="restore-button" @click="restore" style="border: none;background-color: transparent;color: white;margin-top: -0.8rem" icon="el-icon-caret-top">
                    </el-button>
                </div>
            </header>
            <div class="handles" style="margin-bottom: .5rem">操作票名称：
                <input style="border: 1px solid #ccc;color: white;width: 25rem;height: 2rem" v-model="ticketName"/>
            </div>
        <div class="custom-dialog-content" v-if="!isMinimized">
           <div class="txts">
               <div style="display: flex">
                   <div style="width: 10%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0">序号</div>
                   <div style="width: 90%;text-align: center;border-bottom: 1px solid #ccc;padding: 5px 0">内容</div>
               </div>
                   <div v-for="(item,index) in tableData" :key="index" style="display: flex;"     class="table-row"
                        :class="{ selected: selectedRowIndex === item.index } "  @click="selectRow(item.index)">
                       <div style="width: 10%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0">{{item.index}}</div>
                       <div style="width: 90%;border-bottom: 1px solid #ccc;padding: 5px 5px;box-sizing: border-box;white-space: nowrap;overflow-x: auto">{{item.recordDesc}}</div>
                   </div>
           </div>
           <div class="handles">当前操作项：
          <input style="border: 1px solid #ccc;color: white;width: 25rem;height: 2rem" v-model="currentData.recordDesc"/>
               <div class="shuyu">
              <div style="width: 74%;">
                  <div style="height: 10rem;overflow: auto;border: 1px solid #ccc">
                      <div style="text-align: center;border-bottom: 1px solid #ccc;">操作术语</div>
                      <div v-for="(item,index) in shuyuData" :key="index" style="border-bottom: 1px solid #ccc;padding: 2px 2px;white-space: nowrap;overflow-x: auto"  class="table-row"
                           :class="{ selected: selectedSyRowIndex === item.index } "  @click="selectSyRow(item.index)">{{item.recordDesc}}</div>
                  </div>
                  <el-button v-if="!ticketId" size="mini" style="margin-top: .5rem" @click="submitTicket">存为历史操作票</el-button>
                  <el-button v-else size="mini" style="margin-top: .5rem" @click="EditTicket">保存</el-button>
              </div>
                   <div class="btns"  style="width: 24%">
                       <el-radio-group v-model="direction">
                           <el-radio label="qian" style="margin-bottom: .5rem;color: #fff" >向前</el-radio>
                           <el-radio label="hou" style="color: #fff">向后</el-radio>
                       </el-radio-group>
                       <el-button size="mini" style="margin-top: .5rem" @click="insertEvent">插入术语</el-button>
                       <el-button size="mini" style="margin-top: .5rem" @click="addEvent">添加操作</el-button>
                       <el-button size="mini" style="margin-top: .5rem" @click="removeEvent">删除操作</el-button>
                       <el-button size="mini" style="margin-top: .5rem" @click="undo" :disabled="currentIndex <= 0">操作回退</el-button>

                   </div>
               </div>

           </div>
        </div>
    </div>
    </div>
</template>

<style scoped lang="less">
.custom-dialog-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    pointer-events: none;
    color: #fff;
}
.custom-dialog {
    background: rgb(2, 22, 42);
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    pointer-events: auto;
    position: absolute;
    padding: 1rem;
    cursor: move;
    width: 60%;
}
.custom-dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 1.2rem;
    font-weight: bold;
    border-bottom: 1px solid #ebeff0;
    padding-bottom: 0.5rem;
    margin-bottom: 1rem;
}
.header-buttons {
    display: flex;
    gap: 0.5rem;
}
.minimize-button, .restore-button, .close-button {
    background: none;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
    color: white;
}
.custom-dialog-content {
    flex-grow: 1;
    margin-bottom: 1rem;
    font-size: 0.9rem;
    display: flex;
    justify-content: space-between;
}
.txts{
    width: 60%;
    border: 1px solid #ccc;
    height: 15rem;
    overflow: auto;
}
.handles{
    width: 39%;
}
.custom-dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 0.5rem;
}
.table-row {
    display: flex;
    cursor: pointer;
    transition: background-color 0.3s;
}
.table-row:hover {
    background-color: rgb(4, 32, 62); /* 鼠标悬浮时的颜色 */
}
.table-row.selected {
    background-color:rgb(6, 42, 82); /* 选中时的颜色 */
}
.shuyu{
    margin-top: .5rem;
    display: flex;
    justify-content: space-between;
}
.shuyu .el-button{
    color: #ebeff0;
    background: linear-gradient(#176575,#07283f);
    border:0;
    box-shadow: 0 -2px 0 rgba(16, 164, 195, .8);
    margin-left: 0;
}
</style>
